package learnonline.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import learnonline.dao.StudentDao;
import learnonline.dao.TeacherDao;
import learnonline.dao.UserDao;
import learnonline.dao.impl.StudentDaoImpl;
import learnonline.dao.impl.TeacherDaoImpl;
import learnonline.dao.impl.UserDaoImpl;
import learnonline.entity.User;
@WebServlet("/Check-Register")
public class RegisterServlet extends HttpServlet{
	private UserDao userDao=new UserDaoImpl();
	private TeacherDao teacherdao=new TeacherDaoImpl();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		StudentDao studentdao = new StudentDaoImpl();
		String userName=req.getParameter("userName");
		String psw=req.getParameter("passWord");
		String name=req.getParameter("Name");
		int sid = 0; 
		String sname = userName;
		String tname = userName;
		String tdescription = "";
		String timage = "";
		String email = req.getParameter("email");
		double balance = 0.0;
		int identity=Integer.valueOf(req.getParameter("identity"));
		if(userDao.checkUser(userName)!=null){
			req.getRequestDispatcher("register.jsp").forward(req, resp);		
		}else{
			userDao.register(userName, psw, name, identity);
			if(identity==1){
				studentdao.addStudent(sid, sname, email, balance);
			}else if(identity==2){
				teacherdao.addTeacher(0, tname, tdescription, timage);
			}
			
			
			resp.sendRedirect("Login.jsp");
		}
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String userName=req.getParameter("userName");
		String name=req.getParameter("Name");
		PrintWriter out=resp.getWriter();
		User cusername=userDao.checkUser(userName);
		User nickname=userDao.checkNick(name);
		if(cusername!=null){
			out.print(false);	
			out.flush();
			out.close();
		};
		if(nickname!=null){
			out.print(false);
			out.flush();
			out.close();
		}
		out.print(true);	
		out.flush();
		out.close();
			
	}
}
